package multi_thread.basic;

/**
 * @author Cheng Jun
 * Description: 可以利用抛出异常，主动释放锁；
 * 程序出现异常会主动释放锁，这样可以防止死锁的出现；
 * @version 1.0
 * @date 2020/3/1 20:18
 */
public class LockExceptionExample {
    public static void main(String[] args) {
        Test test = new Test();
        Thread thread1 = new Thread(() -> {
            test.run();
        });
        Thread thread2 = new Thread(() -> {
            test.get();
        });

        thread1.start();
        try {
            //确保cpu先执行 thread1
            Thread.sleep(100);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        thread2.start();
    }
}

class Test {
    private int i = 0;

    public synchronized void run() {
        while (true) {
            i++;
            System.out.println(Thread.currentThread().getName() + " run " + i);
            if (i == 10) {
                throw new RuntimeException("出现运行时异常");
            }
        }
    }

    public synchronized void get() {
        System.out.println(Thread.currentThread().getName() + " get i = " + i);
    }
}

